package com.example.webapi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.setting.Setting;
import com.example.webapi.Utils.ResponseModel;
import com.example.webapi.entity.SysUpload;
import com.example.webapi.service.SysUploadService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 上传文件表 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2021-10-28
 */
@RestController
@RequestMapping("/api")
public class SysUploadController {
    @Resource
    SysUploadService uploadService;

    @RequestMapping("upload")
    @ApiOperation(value = "上传文件", notes = "上传附件接口")
    public ResponseModel SaveFiles(@RequestBody MultipartFile file) {

        LocalDateTime localDateTime = LocalDateTime.now();

        String folder = "Project";
        String sFileName = file.getOriginalFilename();

        String sNewFolder = "/" + folder + "/" + localDateTime.getYear() + "/" + localDateTime.getMonthValue();
        // 扩展名
        String fileExt = sFileName.substring(sFileName.lastIndexOf(".") + 1).toLowerCase();
        String newName = UUID.fastUUID().toString().replaceAll("-", "")+ "." + fileExt;

        //读取classpath下的XXX.setting，不使用变量
        Setting setting = new Setting("config/project.setting");
        String basePath = setting.getStr("basePath");
        File file1 = new File(basePath + sNewFolder);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String sNewPath = sNewFolder + "/"  + newName;

        File uploadedFile = new File(basePath, sNewPath);
        try {
            file.transferTo(uploadedFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String projectId = UUID.fastUUID().toString().replaceAll("-", "");
        SysUpload upload = new SysUpload();
        upload.setFileName(newName);
        upload.setFilePath(sNewPath);
        upload.setFileLength(String.valueOf(file.getSize()));
        upload.setState(0);
        upload.setCreateTime(DateUtil.now());
        upload.setProjectId(projectId);
        uploadService.save(upload);
        Map<String,Object> map = new HashMap<>();
        map.put("projectId",projectId);
        map.put("fileId",upload.getId());
        return ResponseModel.success(map);
    }
}
